package com.iukcy.hight.util;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: kbase-demo
 * @description: kbase返回值转java对象工具类
 * @author: zhangzhufu
 * @create: 2020-08-11 10:34:49
 **/
public class ResultSetToBeanUtils {
    /**
     * @Description: resultSet转java bean对象集合
     * @Date: 2020/8/11 14:09
     * @Param: [resultSet, className]
     * @return: java.util.List<T>
     */
    public static <T> List<T> toList(ResultSet resultSet, Class<T> className) {
        List<T> list = new ArrayList();
        Field fields[] = className.getDeclaredFields();
        try {
            while (resultSet.next()) {
                T instance = className.newInstance();
                for (Field field : fields) {
                    Object result = resultSet.getString(field.getName());
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    field.set(instance, result);
                    field.setAccessible(flag);
                }
                list.add(instance);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * @Description: resultSet转java bean对象
     * @Date: 2020/8/11 14:09
     * @Param: [resultSet, className]
     * @return: T
     */
    public static <T> T toObject(ResultSet resultSet, Class<T> className) {
        T instance = null;
        try {
            //默认光标在指向无，读取数据前使用next()方法，移动光标
            if (resultSet.next()) {
                instance = className.newInstance();
                Field fields[] = className.getDeclaredFields();
                for (Field field : fields) {
                    Object result = resultSet.getString(field.getName());
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    field.set(instance, result);
                    field.setAccessible(flag);
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return instance;
    }
}
